#include "rec_read_avi.h"
#include "cross_com.h"

CRecRead_avi::CRecRead_avi(int buf_size,int clientID , int channel)
{
	m_buf_size = 1000 << 10;
	m_frm_buf = new unsigned char[m_buf_size];
}

CRecRead_avi::CRecRead_avi()
{

	m_buf_size = 1000 << 10;
	m_frm_buf = new unsigned char[m_buf_size];
}
CRecRead_avi::~CRecRead_avi()
{
		
}

int CRecRead_avi::Open(const char* file_path, int64_t startTime, int64_t endTime, bool bClearBuf)
{
	int ret = 0;
	int getidx = 1;

	m_fd = AVI_open_input_file(file_path, getidx);

	return 0;
}


void CRecRead_avi::Close(bool bImmediate)
{
	printf("ClientID %02d CH%02d \n",m_clientID,m_channel);
	//CCross_LockAuto tempLock(&m_modeLock);

	m_modeLock.lock();
	if(m_bDownload && !bImmediate)
	{
	    printf("ClientID %02d %02d index %d MkEmptyFrame",m_clientID,m_channel,m_fileIdx);
	}
	AVI_close(m_fd);
	m_fd = NULL;
	m_modeLock.unlock();
	m_fileLen    = 0;
	m_curIndex   = 0;
	m_bDataEnd   = true;
	printf("ClientID %02d %02d index %d CRecReadBase::Close \n",m_clientID,m_channel,m_fileIdx);
}

//每次读取数据，尽量保证缓存读满
int CRecRead_avi::ReadFIFONormal()
{
	//读取大块数据
	int ret = 0;
	int frm_type = PFrame;
	int64_t pts = 0;
	int frm_size = 0;
	char* pAvi_buf = (char*)m_frm_buf;
	int   is_key = 0;
	char* pdest_frm = NULL;
	while (true)
	{
		frm_size = ret = AVI_read_frame(m_fd, pAvi_buf, &is_key);
		if (ret == -1)
		{
			break;
		}
		//full
		if (frm_size > m_pFIFO->GetFreeSize())
		{
			break;
		}
		pdest_frm = pAvi_buf + 4;
		ret = m_pFIFO->WriteFrame((unsigned char*)pdest_frm,m_buf_size, frm_type, pts);
	}
	
	return 0;
}

int CRecRead_avi::ReadFIFO2Forward()
{
	return 0;
}

int CRecRead_avi::ReadFIFOForward()
{
	return 0;
}

int  CRecRead_avi::ReadFIFOReback()
{
	return 0;
}

bool CRecRead_avi::IsOpen()
{
	return true;
}

int CRecRead_avi::SeekToTime(int64_t time, bool bClear )
{
	int ret = 0;

	return ret;
}

int CRecRead_avi::ReadFrame(unsigned char* buf, uint32_t bufLen)
{
	int ret = 0;

	return ret;
}